package com.andooco.dataq.util;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * cvs操作类【此系统把cvs当做本地数据库】
 *
 * @author andooco
 * 20201125
 */

/**
 * 利用javacsv2.0做导入导出csv文件工具类<br/>
 *
 * @author kpchen
 */
@Slf4j
public class CSVUtils {

    private static char separator = ',';
    /**
     * 数据源文件头
     */
    public static String[] HEAD_ARR_DATASOURCE = new String[]{"jdbcType", "jdbcName", "IP", "port", "sidType", "SID", "username", "password"};
    /**
     * 功能块文件头
     */
    public static String[] HEAD_ARR_FUNC = new String[]{"funcName", "funcContent", "funcUid"};
    /**
     * 文件资料文件头
     */
    public static String[] HEAD_ARR_FILE = new String[]{"fileUid", "fileName", "fileType", "uploadDate", "totalPage", "currentPage", "remark", "username"};

    public static void main(String[] args) throws Exception {
//
//        // 测试导出
//        String filePath = "D:/test.csv";
//        List<String[]> dataList = new ArrayList<String[]>();
//        for (int i = 0; i < 10; i++) {
//            dataList.add(new String[]{"0" + i, "小明" + i, "java" + i});
//        }
//        exportCsv(dataList, filePath);
        // 测试导入
        List<String[]> datas = importCsv(CommonConstants.DATA_ROOT_PATH, CommonConstants.JDBC_PATH);
        for (String[] strings : datas) {
            System.out.println(strings[0]);
        }
    }

    /**
     * java导入csv文件
     *
     * @param filePath 导入路径
     * @return
     * @throws Exception
     */
    public static List<String[]> importCsv(String rootPath, String filePath) {
        File rootPathFile = new File(rootPath);
        if (!rootPathFile.exists()) {
            rootPathFile.mkdirs();
        }
        String path = rootPath + filePath;
        File filePathFile = new File(path);
        if (!filePathFile.exists()) {
            try {
                filePathFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        CsvReader reader = null;
        List<String[]> dataList = new ArrayList<String[]>();
        try {
            reader = new CsvReader(path, separator, Charset.forName("utf-8"));

            // 读取表头  加上这一句是不算表头数据从第二行开始取
            reader.readHeaders();
            // 逐条读取记录，直至读完
            while (reader.readRecord()) {
                dataList.add(reader.getRawRecord().split(","));
                // // 下面是几个常用的方法
                // 读取一条记录
//                System.out.println(reader.getRawRecord());
                // 按列名读取这条记录的值
//                System.out.println(reader.get(0));
//                System.out.println(reader.get(1));
            }
        } catch (Exception e) {
            System.out.println("读取CSV出错..." + e);
        } finally {
            if (null != reader) {
                reader.close();
            }
        }

        return dataList;
    }

    /**
     * java导出cvs文件，追加模式
     *
     * @param dataList 数据集
     * @param filePath 导出路径
     * @return
     * @throws Exception
     */
    public static boolean exportCsv(String rootPath, String filePath, List<String[]> dataList) throws Exception {
        boolean isSuccess = false;
        CsvWriter writer = null;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(rootPath + filePath, true);
            writer = new CsvWriter(out, separator, Charset.forName("utf-8"));
            for (String[] strs : dataList) {
                writer.writeRecord(strs);
            }

            isSuccess = true;
        } catch (Exception e) {
            System.out.println("生成CSV出错..." + e);
            throw e;
        } finally {
            if (null != writer) {
                writer.close();
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    System.out.println("exportCsv close Exception: " + e);
                    throw e;
                }
            }
        }
        return isSuccess;
    }

    /**
     * 追加一行csv内容
     *
     * @throws Exception
     */
    public static void writeDataToCsvFile(String rootPath, String filePath, String[] dataList, String[] headArr) {
        File rootPathFile = new File(rootPath);
        if (!rootPathFile.exists()) {
            rootPathFile.mkdirs();
        }
        String path = rootPath + filePath;
        File fileName = new File(path);
        if (!fileName.exists()) {
            try {
                fileName.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        RandomAccessFile randomFile = null;
        try {
            // 打开一个随机访问文件流，按读写方式
            randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数。如果内容为空，先写标题
            if (randomFile.length() == 0) {
                randomFile.writeBytes(String.join(",", headArr));
                randomFile.writeBytes("\r\n");
            }
            // 将写文件指针移到文件尾。
            long fileLength = randomFile.length();
            randomFile.seek(fileLength);
            randomFile.writeBytes(String.join(",", dataList));
            randomFile.writeBytes("\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e) {
                    randomFile = null;
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 处理csv内容
     * appendOrNot为true是为追加模式
     *
     * @throws Exception
     */
    public static void writeDataListToCsvFile(String rootPath, String filePath, List<String[]> dataList, boolean appendOrNot, String[] headArr) {
        File rootPathFile = new File(rootPath);
        if (!rootPathFile.exists()) {
            rootPathFile.mkdirs();
        }
        String path = rootPath + filePath;
        File fileName = new File(path);
        if (fileName.exists() && !appendOrNot) {
            fileName.delete();
        }
        if (fileName.exists() && !appendOrNot) {
            log.error("删除缓存文件失败，查看是否打开了缓存文件：{}", path);
        }
        if (!fileName.exists()) {
            try {
                fileName.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        RandomAccessFile randomFile = null;
        try {
            // 打开一个随机访问文件流，按读写方式
            randomFile = new RandomAccessFile(fileName, "rw");

            // 文件长度，字节数。如果内容为空，先写标题
            if (randomFile.length() == 0) {
                randomFile.writeBytes(String.join(",", headArr));
                randomFile.writeBytes("\r\n");
            }
            // 将写文件指针移到文件尾。
            long fileLength = randomFile.length();
            randomFile.seek(fileLength);

            for (String[] strs : dataList) {
                randomFile.writeBytes(String.join(",", strs));
                randomFile.writeBytes("\r\n");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e) {
                    randomFile = null;
                    e.printStackTrace();
                }
            }
        }
    }
}